/** @jsxImportSource @emotion/react */
import * as React from "react";
import {
    Navbar,
    Toolbar,
    Text,
    Button,
    IconButton,
    MenuList,
    MenuItem,
    useTheme,
    useToast,
    LayerLoading,
    Container,
    IconMoreVertical,
    IconArrowLeft,
    IconArrowRight,
    IconPackage,
    IconTruck,
    Touchable,
    IconRefButton,
    IconCloud,
    TwoHalfRightPanel,
    VerticalMenu,
    DdMenuItem
} from "customize-easy-ui-component";
//import {useAbandonDetail, useFlowReport, useIspDetail} from "./db";
//import { useSession } from "../auth";

//import { Link as RouterLink,  } from "wouter";
import { Link as RouterLink } from "../routing/Link";
import { ContainLine, TransparentInput } from "../comp/base";
import {PreloadedQuery, usePreloadedQuery, useRefetchableFragment} from "react-relay/hooks";
import {IspEntranceQuery} from "../task/device/__generated__/IspEntranceQuery.graphql";
//import {IspDetailQuery} from "./__generated__/IspDetailQuery.graphql";
import useAbandonDetailMutation from "./useAbandonDetailMutation";
import useFlowReportMutation from "./useFlowReportMutation";
//import {DetailReportsQuery} from "./DetailReports";
import {DetailMainQuery} from "./DetailMain";
import {DetailReportsQuery} from "./DetailReports";
import {taskStatusMap} from "../task/TaskList";
import {reportStatusMap} from "../task/DeviceListItem";
import {useContext} from "react";
import RoutingContext from "../routing/RoutingContext";
const graphql = require("babel-plugin-relay/macro");

/*const ispDetailQuery= graphql`
    query IspDetailQuery($id: ID!) {
        node(id: $id) {
            id,
            ... on Detail {
                ident,task{id,date,status,liabler{id,person{id,name}} }
                isp{ id,no,ispDate,
                    dev{id,cod}
                    report{id,stm{id,sta,authr{id,person{id,name}}
                        master{id,person{id,name}}
                    } }
                }
            },
            __typename
        }
    }
`;*/

//[HOOK限制]按钮点击函数内部直接上toast()或toaster.notify()很可能无法正常显示。而放在函数组件顶层render代码前却能正常。
interface IspDetailProps {
  id?: string;   　//来自上级<Route path={"/device/:id/"} component={} />给的:id。
  prepared: {
    query: PreloadedQuery<typeof DetailMainQuery>;
  }
  children: React.ReactNode;
  routeData: any;
}
//右半边页面 ： 左半边算父组件实际是在路由器做的上级路由嵌套组件拼凑成的。
export default function IspDetail(props: IspDetailProps) {
    const data1 = usePreloadedQuery<typeof DetailMainQuery>(
        DetailMainQuery,
        props.prepared.query,
    );
    const [data, refetch] = useRefetchableFragment(
        DetailReportsQuery,
        data1,
    );
    const { node:isp, }=data;
  const theme = useTheme();
  const toast = useToast();
  //getISP(id: $id) 可以用 node( id )替换! 没必要搞那么多接口函数啊。node() 替换掉：getISP(id: $id) {}
  let filtercomp={
    id: props.routeData.params.ispId,
  };
 // const { loading, items:isp , } = useIspDetail(filtercomp);
    const {call:abandonFunc,doing:abandoning, called:abandoned, reset:abandonrest}= useAbandonDetailMutation();
  //reportId: isp?.reps[0]?.id
  /*const {result:flowresp, submit:flowReportFunc, } = useFlowReport({
    reportId: 1520287, memo:'测试期直接删', users:[1,34]
  });                props.routeData.params.ispId
  */
  const {call:flowReportFunc,doing:flowing, called:flowed, reset:flowreset}= useFlowReportMutation();
  console.log("IspDetail页面刷新85 props:", props,",isp=,",isp);
    const { history } = useContext(RoutingContext);

  return (
      <TwoHalfRightPanel
          title={ `检验号${props.routeData.params.ispId}详情向导`
          }
          back={
              <RouterLink href="/inspect">
                  <IconButton  noBind  icon={<IconArrowLeft />}
                               variant="ghost"
                               label="后退"
                               size="md"
                               css={{
                                   marginRight: theme.spaces.sm,
                                   [theme.mediaQueries.md]: {
                                       display: "none"
                                   }
                               }}
                  />
              </RouterLink>
          }
          menu={
              <VerticalMenu>
                  <DdMenuItem label="责任人派工界面加主/分项报告"
                      onClick={()=> history.push(`/inspect/${props.routeData.params.ispId}/addReport`)
                      } />
                  <DdMenuItem label="整个检验报告流转(含分项)"
                      onClick={()=> flowReportFunc( isp?.report?.id!, "/inspect/fCfLZtwOQ_6HPHewrbtGZUlzcA/report/fc25TU-9Tb6RopbXtb4Ws1JlcG9ydA",
                      "统一",3)
                      } />
              </VerticalMenu>
          }
      >
          <div
              css={{
                  width:'100%',
              }}
          >
              <Text variant="h5">该次检验的基本概况</Text>
              <div>
                  <ContainLine display={'设备号,标识:'}>
                      <TransparentInput  readOnly
                                         value={ isp?.dev?.cod || isp?.bus?.ident! ||''}
                      />
                  </ContainLine>
                  <ContainLine display={'报告编号'}>
                      <TransparentInput readOnly value={ isp?.no ||'' }/>
                  </ContainLine>
                  <ContainLine display={'任务日期'}>
                      <TransparentInput readOnly value={ isp?.bus?.task?.date ||'' }/>
                  </ContainLine>
                  <ContainLine display={'检验日期'}>
                      <TransparentInput readOnly value={ isp?.ispDate ||'' }/>
                  </ContainLine>
                  <ContainLine display={'任务状态'}>
                      <TransparentInput readOnly value={taskStatusMap.get(isp?.bus?.task?.status!) ||'' }/>
                  </ContainLine>
                  <ContainLine display={'报告流转状态'}>
                      <TransparentInput readOnly value={reportStatusMap.get(isp?.report?.stm?.sta!) ||'' }/>
                  </ContainLine>
                  <div>
                      <ContainLine display={'责任人'}>
                          <TransparentInput  readOnly  placeholder="责任人"
                                             value={isp?.bus?.task?.liabler?.person?.name ||''}
                          />
                      </ContainLine>
                      <ContainLine display={'报告校核人'}>
                          <TransparentInput  readOnly  placeholder="报告校核人"
                                             value={isp?.report?.stm?.master?.person?.name ||''}
                          />
                      </ContainLine>
                      <ContainLine display={'检验人员:'}>
                          <Text  placeholder="所有参与检验人"
                                 css={{
                                     display: 'block',
                                     width: '100%',
                                 }}
                          >
                              {isp?.report?.stm?.authr?.map((one :any, i: any) => {
                                  return (
                                      <RouterLink key={i}  href="/inspect/">
                                          <Button
                                              size="md"
                                              variant="ghost"
                                              intent="none"
                                              iconAfter={<IconArrowRight />}
                                          >{one.person.name ||''}
                                          </Button>
                                      </RouterLink>
                                  )
                              } )}
                          </Text>
                      </ContainLine>

                  </div>

                  <div css={{
                      display: 'flex',
                      flexWrap: 'wrap',
                      justifyContent: 'center',
                      alignItems: 'center',
                      lineHeight: '3rem',
                  } }>
                      <RouterLink href={`/task/${isp?.bus?.task?.id}/detail/${isp?.bus?.id}`}>
                          <Button noBind  intent="primary"
                                  iconAfter={<IconArrowRight/>}
                          >
                           去任务明细和收费
                          </Button>
                      </RouterLink>
                  </div>
              </div>


          </div>

          {!isp && <React.Fragment>
              <Text  variant="h4"　css={{ textAlign: 'center' }}>
                  没找到该ISP,请刷新
              </Text><br/>
              <RouterLink href="/inspect/">
                  <Button
                      size="lg" noBind
                      intent="primary"
                      iconBefore={<IconTruck />}
                      iconAfter={<IconArrowRight />}
                  >
                      后退刷新
                  </Button>
              </RouterLink>
          </React.Fragment>
          }
          <LayerLoading loading={abandoning || flowing} />
      </TwoHalfRightPanel>
  );
};

